import {get, post} from './http.js';

$(document).ready(function () {
    // 获取商品ID
    const urlParams = new URLSearchParams(window.location.search);
    const productId = urlParams.get('id');

    // 模拟获取商品详情数据
    var productDetail = null;
    // {
    //     id: productId,
    //     title: "Apple iPhone 15 Pro Max",
    //     desc: "限时优惠，赠送价值299元无线充电器",
    //     price: 9999.00,
    //     images: [
    //         "images/product1-1.png",
    //         "images/product1-2.png",
    //         "images/product1-3.png",
    //         "images/product1-4.png"
    //     ],
    //     options: [{name: "颜色",values: [{"specValueId":111,"specValueName":"暗紫色"}, {"specValueId":112,"specValueName":"银色"}, {"specValueId":113,"specValueName":"金色"}, {"specValueId":114,"specValueName":"蓝色"}]},{name: "容量",values: [{"specValueId":115,"specValueName":"128GB"}, {"specValueId":116,"specValueName":"256GB"}, {"specValueId":117,"specValueName":"512GB"}, {"specValueId":118,"specValueName":"1TB"}]}],
    //     detail: "这里是商品详细介绍...",
    //     params: [
    //         { name: "品牌", value: "Apple" },
    //         { name: "型号", value: "iPhone 15 Pro Max" },
    //         { name: "颜色", value: "暗紫色" },
    //         { name: "容量", value: "128GB" }
    //     ],
    //     "specValueIdMap":{"1932651432921403397:1932651432921403115": "1932651433114341387"}
    // };

    get('/api/sku/search/detail/' + productId).then(data => {
        productDetail = data;

        // 初始化页面
        renderProduct();
        initEvents();
    })
        .catch(
            error => {
                alert("出错了...");
            }
        )

    // 渲染商品信息
    function renderProduct() {
        // 渲染标题和描述
        $('.product-title').text(productDetail.title);
        $('.product-desc').text(productDetail.desc);

        // 渲染价格
        $('.price .value').text(productDetail.price.toFixed(2));

        // 渲染图片
        $('.main-img').attr('src', productDetail.images[0]);

        // 渲染缩略图
        const $thumbList = $('.thumb-list');
        productDetail.images.forEach((img, index) => {
            $thumbList.append(`
                <div class="thumb-item ${index === 0 ? 'active' : ''}" data-index="${index}">
                    <img src="${img}" alt="">
                </div>
            `);
        });

        // 渲染规格选项
        productDetail.options.forEach(option => {
            const $optionGroup = $(`
                <div class="option-group" style="margin-bottom: 10px;">
                    <span class="label">${option.name}</span>
                    <div class="choose-options">
                        ${option.values.map((value, index) => `
                            <span class="option-item ${index === 0 ? 'active' : ''}" data-specValueId=${value.specValueId}>${value.specValueName}</span>
                        `).join('')}
                    </div>
                </div>
            `);
            $('.choose-area').append($optionGroup);
        });

        // 渲染商品详情
        $('#detail').html(productDetail.detail);

        // 渲染规格参数
        const $paramsTable = $('<table class="params-table"></table>');
        productDetail.params.forEach(param => {
            $paramsTable.append(`
                <tr>
                    <td class="param-name">${param.name}</td>
                    <td class="param-value">${param.value}</td>
                </tr>
            `);
        });
        $('#params').append($paramsTable);
    }

    // 获取选中的规格选项
    function getSelectedOptions() {
        const selectedOptions = {};
        $('.option-group').each(function () {
            const optionName = $(this).find('.label').text();
            const selectedValue = $(this).find('.option-item.active').data('specvalueid');
            selectedOptions[optionName] = selectedValue;
        });
        return selectedOptions;
    }

    // 根据选中的规格选项获取对应的SKU ID
    function getSkuId() {
        const selectedOptions = getSelectedOptions();

        // 将选中的规格选项的specValueId拼接成字符串
        const specValueIds = Object.values(selectedOptions);
        const specValueIdsStr = specValueIds.join(':');


        // 从productDetail的specValueIdMap中获取对应的skuId
        const skuId = productDetail.specValueIdMap[specValueIdsStr];

        const sku = productDetail.skuList.find(sku => sku.skuId === skuId);
        return sku;
    }

    // 初始化事件
    function initEvents() {
        // 缩略图切换
        $('.thumb-item').click(function () {
            const index = $(this).data('index');
            $('.thumb-item').removeClass('active');
            $(this).addClass('active');
            $('.main-img').attr('src', productDetail.images[index]);
        });

        // 规格选择
        $('.option-item').click(function () {
            $(this).parent().find('.option-item').removeClass('active');
            $(this).addClass('active');

            // 获取选中的选项值(规格值的唯一标识ID)
            var specvalueid = $(this).data("specvalueid");
            const sku = getSkuId();

            $('.price .value').text(sku.skuPrice.toFixed(2));
        });

        // 数量加减
        $('.minus').click(function () {
            let num = parseInt($('.number-input').val());
            if (num > 1) {
                $('.number-input').val(num - 1);
            }
        });

        $('.plus').click(function () {
            let num = parseInt($('.number-input').val());
            $('.number-input').val(num + 1);
        });

        // 选项卡切换
        $('.tab-item').click(function () {
            const index = $(this).index();
            $('.tab-item').removeClass('active');
            $(this).addClass('active');
            $('.tab-pane').removeClass('active');
            $('.tab-pane').eq(index).addClass('active');
        });

        // 立即购买（跳转到去订单页面）
        $('.btn-buy').click(function () {
            // 获取数量
            const count = parseInt($('.number-input').val());
            // 从productDetail的specValueIdMap中获取对应的skuId
            var sku = getSkuId();

            // 构建URL参数
            let urlParams = `spuId=${productDetail.id}&skuId=${sku.skuId}&count=${count}&from=productDetail`;
            window.location.href = `order.html?${urlParams}`;
        });

        // 加入购物车
        $('.btn-cart').click(function () {
            // 获取数量
            const count = parseInt($('.number-input').val());
            // 从productDetail的specValueIdMap中获取对应的skuId
            var sku = getSkuId();

            // 构建URL参数
            let urlParams = `spuId=${productDetail.id}&skuId=${sku.skuId}&count=${count}`;

            const obj = {
                spuId: productDetail.id,
                skuId: sku.skuId,
                quantity: count
            };

            // 添加商品到购物车
            post('/api/cart/add', obj).then(res => {
                Notify.success('添加成功');
                // 跳转到购物车页面
                window.location.href = `cart.html?${urlParams}`;
            });


        });
    }


}); 